package org.cy.peoplehill.server;

import org.cy.peoplehill.client.LoginService;
import org.cy.peoplehill.client.User;
import org.cy.peoplehill.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		LoginService {

	public User Login(User user) throws IllegalArgumentException {
		// Escape data from the client to avoid cross-site script vulnerabilities.
		String userName = escapeHtml(user.getName());
		
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(userName)) {
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}
		
		UserManager userMgr = UserManager.getManager();
		
		// Verify that the user name is duplicated.
		if (userMgr.isExist(user)){
			throw new IllegalArgumentException(
				"Name already exists");			
		}
		
		userMgr.addUser(user);
		return user;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
